#!/usr/bin/env node

/*
 * dataencrypt - data encryptor
 *
 * Copyright (c) 2016 Kenji Urushima (kenji.urushima@gmail.com)
 *
 * This software is licensed under the terms of the MIT License.
 * https://kjur.github.io/jsrsasign/license
 *
 * The above copyright and license notice shall be 
 * included in all copies or substantial portions of the Software.
 * 
 * Please use '-h' option for this script usage.
 * ---------------------------------------------------------
 * DESCRIPTION
 *   This script encrypts a plain text or data file with
 *   RSA or RSA-OAEP algorithm.
 *
 * USAGE
 *   % dataencrypt data.txt enc.bin rsapub.pem RSA  # with RSA alg
 *   % dataencrypt data.txt enc.bin rsapub.pem RSAOAEP  # with RSA-OEAP alg
 *   % dataencrypt data.txt enc.bin rsapub.pem RSAOAEP256  
 *     # with RSA/ECB/OAEPWithSHA-256AndMGF1Padding 
 */

var program = require('commander');
var rs = require('jsrsasign');
var rsu = require('jsrsasign-util');
var path = require('path');

program
  .version('1.0.0 (2016-Nov-05)')
  .usage('[options] <input plain file> <output encrypted file> <PEM RSA public key file> [RSA|RSAOAEP*]')
  .description('encrypt data')
  .parse(process.argv);

if (program.args.length < 3)
  throw "wrong number of arguments";

var keyObj, inStr, encHex;
var algName = "RSA";
var keyStr = "";
var inFileOrStr = program.args[0];
var outFile = program.args[1];
var keyFileOrStr = program.args[2];
if (program.args.length > 3) algName = program.args[3];

try {
  keyStr = rsu.readFile(keyFileOrStr);
} catch(ex) {
  keyStr = keyFileOrStr;
}

try {
  inStr = rsu.readFile(inFileOrStr);
} catch(ex) {
  inStr = inFileOrStr;
}

try {
  keyObj = rs.KEYUTIL.getKey(keyStr);
} catch(ex) {};

if (keyObj instanceof rs.RSAKey && keyObj.isPublic) {
  encHex = rs.KJUR.crypto.Cipher.encrypt(inStr, keyObj, algName);
  rsu.saveFileBinByHex(outFile, encHex);
  console.log("data encrypted successfully");
} else {
  console.log("data encryption failed");
}





